package com.yjs.app.trade.core.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;

/**
 * 字符串工具类
 * 
 * @author hikaru
 * @since 1.0.0
 */
public class StringUtil extends StringUtils {
	
	public StringUtil(String separator) {
		SEPARATOR = separator;
	}

	/**
	 * 全局分隔符
	 */
	public static String SEPARATOR;
	
	/**
	 * 获取32位UUID
	 */
	public static String getUUID() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
	
	/**
	 * 根据文件名获取文件类型
	 */
	public static String getFileTypeByFileName(String fileName) {
		String fileType = "";
		if (!isEmpty(fileName) && fileName.contains(".")) {
			fileType = fileName.substring(fileName.lastIndexOf("."));
		}
		return fileType;
	}
	
	public static String getServiceName(Class<?> clazz) {
		return uncapitalize(clazz.getSimpleName()) + "Service";
	}
	
	/**
	 * 将驼峰命名改为下划线命名
	 * 
	 * @param name 原字符串
	 * @param isUpperCase 是否大写
	 */
	public static String changeCamelCaseToUnderscores(String str, boolean isUpperCase) {
		if (isBlank(str)) {
			return str;
		} else {
			StringBuffer newStr = new StringBuffer(); 
			char[] charArray = str.toCharArray();
			newStr.append(charArray[0]);
			if (charArray.length > 1) {
				for (int i = 1; i < charArray.length; i++) {
					char c = charArray[i];
					if (c == Character.toUpperCase(c) && c != '_') {
						newStr.append("_");
					}
					newStr.append(c);
				}
			}
			if (isUpperCase) {
				return newStr.toString().toUpperCase();
			} else {
				return newStr.toString().toLowerCase();
			}
		}
	}
	
	/**
	 * 将驼峰命名改为下划线命名（默认大写）
	 * 
	 * @param name 原字符串
	 */
	public static String changeCamelCaseToUnderscores(String str) {
		return changeCamelCaseToUnderscores(str, true);
	}
	
	/**
	 * 是否空白字符串
	 */
	public static boolean isBlank(String str) {
		return (str == null || "".equals(str.trim()));
	}
	
	/**
	 * setter method name
	 * 
	 * @param fieldName 字段名称
	 */
	public static String setterMethodName(String fieldName) {
		if (isBlank(fieldName)) {
			throw new IllegalArgumentException("field name can not be blank");
		} else {
			return "set" + capitalize(fieldName);
		}
	}
	
	/**
	 * getter method name
	 * 
	 * @param fieldName 字段名称
	 */
	public static String getterMethodName(String fieldName) {
		if (isBlank(fieldName)) {
			throw new IllegalArgumentException("field name can not be blank");
		} else {
			return "get" + capitalize(fieldName);
		}
	}
	
	/**
	 * 获取参数化的消息
	 * 
	 * @param message 消息
	 * @param args 参数
	 * @return 参数化的消息
	 */
	public static String getMessage(String message, String ... args) {
		if (isBlank(message)) {
			return null;
		}
		if (!ArrayUtil.isEmpty(args)) {
			for (int i = 0; i < args.length; i++)
				message = message.replace("{" + i + "}", args[i]);
		}
		return message;
	}
	
	/**
	 * 获取第一个non-blank的值
	 */
	public static String getNonBlankValue(String ... stringArray) {
		if (!ArrayUtil.isEmpty(stringArray)) {
			for (String string : stringArray) {
				if (!isBlank(string)) {
					return string;
				}
			}
		}
		return null;
	}
	
	/**
	 * trim string
	 */
	public static String trim(String string) {
		return string == null ? null : string.trim();
	}
	
	public static String base64Encode(String value) {
		return Base64Utils.encodeToString(value.getBytes());
	}
	
	public static String base64Decode(String value) {
		try {
			return new String(Base64Utils.decodeFromString(value), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String thumb(String path, int width, int height) {
		if (!isBlank(path)) {
			path = path.replaceAll("http://image", "http://thumb");
			String suffix = path.substring(path.lastIndexOf("."));
			path += "@1e";
			if (width != 0) {
				path +=  "_" + width + "w";
			}
			if (height != 0) {
				path += "_" + height + "h";
			}
			path += suffix;
			return path;
		}
		return null;
	}
	
	/**
	 * 将分钟数格式化成小时数
	 * 
	 * @param minutes
	 */
	public static long formatMinutesToHours(long minutes) {
		return (long) Math.rint(minutes / 60.0);
	}
	
	/**
	 * 替换文本
	 * 
	 * @param text
	 * @param searchArray
	 * @param replaceArray
	 */
	public static String replaceEach(String text, String[] searchArray, String[] replaceArray) {
		return org.apache.commons.lang3.StringUtils.replaceEach(text, searchArray, replaceArray);
	}
	

	public static String[] splitByLength(String data, int length) {
		List<String> dataList = new ArrayList<String>();
		int totalLength = data.length();
		totalLength -= totalLength % length;
		if (totalLength / length == 0) {
			throw new IllegalArgumentException("data的长度不足length的一倍");
		}
		if (length > 0 && !isEmpty(data)) {
			int index = 0;
			while (index < totalLength) {
				dataList.add(data.substring(index, index += length));
			}
		}
		return dataList.toArray(new String[]{});
	}
	
	public static String urlEncode(String data) {
		try {
			return URLEncoder.encode(data, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
